# -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
import datetime
import func
from django.db.models import Q,Sum

url_base = '/erp'

class MoneyField(models.DecimalField):
    
    def __init__(self, *args, **kwargs):
        # Default to the max size for SQL Server's money datatype
        kwargs['max_digits'] = kwargs.get('max_digits', 20)
        kwargs['decimal_places'] = kwargs.get('decimal_places', 2)
        super(MoneyField, self).__init__(*args, **kwargs)
    
    def get_placeholder(self, value):
        return r'CONVERT(money, %s)'


GENDER_CHOICES = (
        ('M', '男'),
        ('F', '女'),         
     )

class Employee(models.Model):
    """
            员工表
    """
    Dep_CHOICES = ( ('E','工程部'),('P','采购部') ,('M','管理部'),('A','财务部'),('S','仓管部')   )
        
    #Emp_ID = models.CharField("员工编号",max_length=50,unique=True)
    Emp_Name = models.CharField("姓名",max_length=20)
    Emp_Gender= models.CharField("性别", max_length=1, choices=GENDER_CHOICES,null=True, blank=True,)
    Emp_From = models.CharField("籍贯",max_length=20,null=True, blank=True, )
    Emp_User = models.ForeignKey(User ,verbose_name='登录帐号', unique=True, related_name='帐号',null=True, blank=True, on_delete=models.SET_NULL)
    Emp_Department = models.CharField("部门", max_length=1, choices=Dep_CHOICES,null=True, blank=True,)
    @property
    def get_url(self):
        return url_base + '/employee/'+str(self.id)
    
    def __unicode__(self):
        return self.Emp_Name
    class Meta: 
        verbose_name = "员工" 
        verbose_name_plural = "员工"
    @staticmethod
    def GetEmployeeFromUser(myUser):
        id = myUser.id
        return Employee.objects.get(Emp_User__id=id)

class Category(models.Model):
    """
    商品分类（编码，名称，上级分类，备注）
    """
    Cate_Name = models.CharField("名称",max_length=50)
    Cate_Parent = models.ForeignKey('self','id' , verbose_name='上级分类', related_name='下级分类',null=True,blank=True)
    Cate_Memo = models.CharField("备注",max_length=100,null=True,blank=True)
    
    def __unicode__(self):
        return self.Cate_Name
    class Meta: 
        verbose_name = "商品分类" 
        verbose_name_plural = "商品分类"
        
class Commodity(models.Model): 
    """
          商品(商品编码，条形码，商品名称，规格，计量单位，有效期，参考价，类别名称)
    """
    #Com_ID = models.CharField("商品编码",max_length=50,unique=True)    
    Com_Name =  models.CharField("商品名称",max_length=50,unique=True,blank=False)
    Com_BarCode =  models.CharField("条形码",max_length=50)
    Com_SPEC =  models.CharField("规格",max_length=50,blank=False)
    Com_Unit =  models.CharField("计量单位",max_length=10,blank=False)
    Com_Expire =  models.CharField("有效期",max_length=10,blank=False)
    Com_Price = MoneyField("参考价") 
    Com_Category =  models.ForeignKey(Category ,verbose_name='商品分类', related_name='商品',null=True,blank=True)
    
    def _get_stock(self):
        income=PurchaseReceiptDetail.objects.filter(Q(PurchaseReceipt__PR_Ststus='P')&Q(Commodity=self)).aggregate(Sum('Quanlity'))
        outcome=StockOutItem.objects.filter(Q(StockOut__Ststus='O')&Q(Commodity=self)).aggregate(Sum('Quanlity'))
        #import logging
        #logging.error(income['Quanlity__sum'])
        #logging.error(outcome.Quanlity__sum)
        return int((income['Quanlity__sum'] if income['Quanlity__sum'] else 0) - (outcome['Quanlity__sum'] if outcome['Quanlity__sum'] else 0)) 
        #return 111
    
    #def _set_stock(self, quantity):
    #    pass    
    #Stock = property(_get_stock, _set_stock)
    Stock = property(_get_stock)
    
    
    def __unicode__(self):
        return self.Com_Name
    class Meta: 
        verbose_name = "商品" 
        verbose_name_plural = "商品"
    
class Customer(models.Model):
    """   
          客户(客户编号,客户名称,联系人)
    """
    CST_Name = models.CharField("客户名称",max_length=100,unique=True)
    CST_Contact = models.CharField("联系人",max_length=100)
    def __unicode__(self):
        return self.CST_Name
    class Meta: 
        verbose_name = "客户" 
        verbose_name_plural = "客户"

class OperatorLog(models.Model):
    """   
          操作日志(操作对象,操作名称,操作时间,操作人,备注)
    """
    OL_OBJ_CHOICES = (
        ('PR', '采购申请'),
        ('PO', '采购订单'),
        ('PA', '付款申请'),
        ('RE', '采购收货'),
        ('SN', '销售出库'),
        #('C', '取消'),
     )
    OL_Obj = models.CharField("操作对象",max_length=2, choices=OL_OBJ_CHOICES,blank=False, null=False)
    OL_Obj_id = models.IntegerField('操作对象ID',blank=False, null=False)
    OL_Name = models.CharField("操作名称",max_length=100,)
    OL_DateTime = models.DateTimeField("操作时间",auto_now_add=True)
    OL_Employee = models.ForeignKey(Employee ,verbose_name='操作人', related_name='操作日志',blank=False)
    OL_Description = models.CharField("备注",max_length=1000)
    class Meta: 
        verbose_name = "操作日志" 
        verbose_name_plural = "操作日志"
    @staticmethod
    def WriteOperatorLog(OL_Obj,name,user,description,OL_Obj_id):
        ol = OperatorLog()
        ol.OL_Obj = OL_Obj
        ol.OL_Name = name
        ol.OL_Employee = Employee.GetEmployeeFromUser(user)
        ol.OL_Description = description
        ol.OL_Obj_id = OL_Obj_id
        ol.save()
    @staticmethod
    def GetOperatorLog(Obj,Obj_id):
        return OperatorLog.objects.filter(OL_Obj=Obj ,OL_Obj_id=Obj_id).order_by('OL_DateTime')
        #return OperatorLog.objects.all().order_by('OL_DateTime')
    
class Project(models.Model):
    """
        项目
    """
    Name = models.CharField("项目名称",max_length=100)
    Customer = models.ForeignKey(Customer ,verbose_name='客户', related_name='项目', null=True,blank=True)
    Manager = models.ForeignKey(Employee ,verbose_name='负责人', related_name='负责项目',blank=False)
    Address = models.CharField("项目所在地",max_length=100)
    CreateDateTime = models.DateTimeField("开始时间",auto_now_add=True)
    FinishDateTime = models.DateTimeField("完工时间", null=True,blank=True)
    Description = models.CharField("备注",max_length=1000,null=True,blank=True)
    
    def __unicode__(self):
        return self.Name
    @property
    def Fee(self):
        sum = PurchaseOrderDetail.objects.filter(Q(POD_PurchaseOrder__Project=self) & Q(POD_PurchaseOrder__PO_Ststus='F')).aggregate(Sum('POD_Amount'))
        return int((sum['POD_Amount__sum'] if sum['POD_Amount__sum'] else 0))
                   
    class Meta: 
        verbose_name = "项目" 
        verbose_name_plural = "项目"
class base_user():
    _user = None
    def _set_user(self,value):
        self._user = value
    def _get_user(self):
        return self._user
    user = property(_get_user,_set_user)
    
class BaseStatus():
    #PropertyList=[]
    def __init__(self, o,user ):        
        #self.user = user
        setattr(o,'user',user)
        self.Obj = o
        
        #for item in PropertyList:
        #    setattr(self,item,getattr(o,item))
            
    def __getattr__(self,name):
        return getattr(self.Obj,name)
        
PurchaseRequestStatusList =[('Can_Submit','submit','提交'),
                            ('Can_Cancel','cancel','取消'),
                            ('Can_Return','return','退回'),
                            ('Can_Audit','pass','通过'),
                            ('Can_Audit','deny','否决'),
                            ('Can_Order','order','下订单'),
                            ]
        
PR_STATUS_CHOICES = ( 
        ('I', '创建中'),('S', '已提交'), ('D', '被否决'), ('P', '已通过'),
          ('B', '已退回'),  ('C', '已取消'), ('O', '已建订单')
     )

class PurchaseRequest(base_user,models.Model):
    """
          采购申请单(采购申请单编号,用途,制单日期,申请人,申请时间,审批人,审批时间,状态,备注)
    """
    
    PR_Use = models.CharField("标题",max_length=500)
    PR_Customer = models.ForeignKey(Customer ,verbose_name='客户', related_name='采购申请单',blank=True,null=True,)
    PR_Project = models.ForeignKey(Project , verbose_name='项目',related_name='采购申请单',blank=True,null=True,)
    PR_DateTime = models.DateTimeField("制单日期",auto_now_add=True)    
    PR_Apply_User = models.ForeignKey(Employee ,verbose_name='申请者', related_name='采购申请单',blank=False, null=False)
    PR_Apply_Date = models.DateTimeField("申请时间",auto_now_add=True)
    PR_Adult_User = models.ForeignKey(Employee , verbose_name='审批者',related_name='审批采购申请单',blank=True, null=True, on_delete=models.SET_NULL)
    PR_Adult_Date = models.DateTimeField("审批时间",blank=True,null=True)
    PR_Ststus = models.CharField("状态",max_length=1, choices=PR_STATUS_CHOICES,default='I',blank=False, null=False)
    PR_Description = models.CharField("备注",max_length=1000,blank=True,null=True)
    PR_LastModify_Date = models.DateTimeField("最后操作时间",blank=False,null=False,auto_now=True)
    
     
    @property
    def get_url(self):
        return url_base + '/pr/'+str(self.id)
    def __unicode__(self):
        return self.PR_Use
    @property    
    def LastModify_Date(self):
        return self.PR_LastModify_Date
    @property    
    def ApplyMan(self):
        return self.PR_Apply_User
    @property    
    def Title(self):
        return self.PR_Use
    @property
    def Status(self):
        return self.PR_Ststus
    @property
    def get_Status_display(self):
        return self.get_PR_Ststus_display
    class Meta:
        permissions = (             
        )
    
        verbose_name = "采购申请" 
        verbose_name_plural = "采购申请"
    
    @property
    def Can_Edit(self):
        return self.user==self.PR_Apply_User.Emp_User and self.PR_Ststus in ['I','B'] 
    @property  
    def Can_Cancel(self):
        return self.user==self.PR_Apply_User.Emp_User and self.PR_Ststus in ['I','S','P','B'] 
    @property
    def Can_Submit(self):
        return self.user==self.PR_Apply_User.Emp_User and self.PR_Ststus in ['I','B']  
    @property
    def Can_Audit(self):
        return self.user==self.PR_Adult_User.Emp_User and self.PR_Ststus in ['S']  
    @property
    def Can_Return(self):
        return( func.in_group(self.user, u'采购') and self.PR_Ststus in ['P']) or (self.user==self.PR_Adult_User.Emp_User and self.PR_Ststus in ['S']) 
    @property
    def Can_Order(self):#采购，通过状态
        return (func.in_group(self.user, u'采购')  and self.PR_Ststus in ['P'])

    def Do(self,user,action):
        action = action.lower()
        if (action=='pass'):
            #通过：审批人可以操作，要写操作日志
            if self.Can_Audit:
                self.PR_Ststus = 'P'
                self.PR_Adult_Date= datetime.datetime.now()
                self.save()
                self.WriteOperatorLog('审批通过',user,'')            
        elif (action=='deny'):
            #拒绝：审批人/采购 可以操作，要写操作日志
            if self.Can_Audit:
                self.PR_Ststus = 'D'
                self.PR_Adult_Date= datetime.datetime.now()
                self.save()
                self.WriteOperatorLog('审批否决',user,'')
        elif (action=='submit'):
            #提交：建立者 可以操作，要写操作日志
            if self.Can_Submit:
                self.PR_Ststus = 'S' 
                self.save()
                self.WriteOperatorLog('提交',user,'')
        elif (action=='return'):
            #退回：审核人和采购 可以操作，要写操作日志
            if self.Can_Return:
                self.PR_Ststus = 'B' 
                self.save()
                self.WriteOperatorLog('退回',user,'退回之后可以重新修改之后再提交')
        elif (action=='cancel'):
            #退回：申请人 可以操作，要写操作日志
            if self.Can_Cancel:
                self.PR_Ststus = 'C' 
                self.save()
                self.WriteOperatorLog('取消',user,'')
        elif (action=='order'):
            #建订单：采购 可以操作，要写操作日志
            if self.Can_Order:                
                #新建订单
                po = PurchaseOrder()
                po.PO_Title = self.PR_Use
                po.PO_Employee = Employee.GetEmployeeFromUser(user)
                po.PO_PurchaseRequest = self
                po.Project = self.PR_Project
                po.PO_Ststus = 'I'
                po.save()
                #订单项目
                for item in PurchaseRequestItems.objects.filter(PRI_PurchaseRequest=self):
                    pod = PurchaseOrderDetail()
                    pod.POD_PurchaseOrder = po
                    pod.POD_Amount = item.PRI_Amount
                    pod.POD_Commodity = item.PRI_Commodity
                    pod.POD_Price = item.PRI_Price
                    pod.POD_Quanlity = item.PRI_Quanlity
                    pod.save()
                #修改状态
                self.PR_Ststus = 'O' 
                self.save()
                self.WriteOperatorLog('已建订单',user,'')
        else:
            pass
    def WriteOperatorLog(self,name,user,description):
        OperatorLog.WriteOperatorLog('PR', name, user, description,self.id)
        
    def GetOperatorLog(self):
        return OperatorLog.GetOperatorLog('PR', self.id)
    
    def save(self, *args, **kwargs):
        #do_something() 
        IsNew = False
        if self.id==None:
            IsNew = True
        super(PurchaseRequest, self).save(*args, **kwargs) # Call the "real" save() method.
        #do_something_else()
        if IsNew:
            self.WriteOperatorLog('新建',self.PR_Apply_User.Emp_User,'')
            
class PurchaseRequestItems(models.Model):
    """
          采购申请单条目
    """
    PRI_PurchaseRequest = models.ForeignKey(PurchaseRequest,verbose_name='采购申请',related_name="采购申请单条目")
    PRI_Commodity = models.ForeignKey( Commodity ,verbose_name='物品', related_name = "采购申请单条目")
    PRI_Quanlity = models.IntegerField("数量")
    PRI_Price = models.DecimalField("预估单价",max_digits=20,decimal_places=2,default=0)
    PRI_Amount = models.DecimalField("金额",max_digits=20,decimal_places=2,default=0)
    
    def save(self, *args, **kwargs):
        #do_something() 
        #self.PRI_Price = self.PRI_Commodity.Com_Price
        self.PRI_Amount = self.PRI_Quanlity*self.PRI_Price
        super(PurchaseRequestItems, self).save(*args, **kwargs) # Call the "real" save() method.
        #do_something_else()

class Supplier(models.Model):
    """
            供应商（供应商编号，供应商名称，供应商地址，电话，邮编，地区，
                            传真，开户行名称，开户行账号，联系人，联系人电话）
            """
    SP_Name = models.CharField("供应商名称",max_length=50,null=False)
    SP_Address = models.CharField("供应商地址",max_length=50,null=True,blank=True,)
    SP_Tel = models.CharField("电话",max_length=50,null=True,blank=True,)
    SP_ZipCode = models.CharField("邮编",max_length=50,null=True,blank=True,)
    SP_Area = models.CharField("地区",max_length=50,null=True,blank=True,)
    SP_Fax = models.CharField("传真",max_length=50,null=True,blank=True,)
    SP_Bank = models.CharField("开户行名称",max_length=50,null=True,blank=True,)
    SP_BankUser = models.CharField("开户行账号",max_length=50,null=True,blank=True,)
    SP_Contact = models.CharField("联系人",max_length=50,null=True,blank=True,)
    SP_ContactPhone = models.CharField("联系人电话",max_length=50,null=True,blank=True,)
    #SP_Bank = models.CharField("开户行账号",max_length=50,unique=True)
    def __unicode__(self):
        return self.SP_Name
    
    class Meta: 
        verbose_name = "供应商" 
        verbose_name_plural = "供应商"
        
PO_STATUS_CHOICES = (
        ('I', '创建中'),
        ('S', '已提交'),
        ('D', '被否决'),
        ('P', '已通过'),
        ('C', '已取消'),
        ('B', '被退回'),
        ('Z', '采购中'),
        ('F', '已完成'),
     )

PurchaseOrderStatusList =[('Can_Submit','submit','提交'),
                            ('Can_Cancel','cancel','取消'),
                            ('Can_Return','return','退回'),
                            ('Can_Audit','pass','通过'),
                            ('Can_Audit','deny','否决'),
                            
                            ('Can_Buy','buy','采购'),
                            ('Can_Receipt','receipt','收货'),
                            ('Can_Pay','pay','创建一笔支付'),
                            ]
class PurchaseOrder(base_user, models.Model):
    """
            采购订单（采购订单编号,制单日期,制单人,状态，备注）
            """    
    PO_Title = models.CharField("标题",max_length=50, )
    PO_ReceiptDateTime = models.DateTimeField("交货日期",null=True,blank=True,)
    PO_DateTime = models.DateTimeField("制单日期",auto_now_add=True)
    PO_Employee = models.ForeignKey(Employee,verbose_name='申请者',related_name="采购订单")   #采购员
    PO_Employee_Audit= models.ForeignKey(Employee,verbose_name='审核者',related_name="审核采购订单",null=True,blank=True,)   #采购员
    PO_Supplier = models.ForeignKey(Supplier,verbose_name='供应商',related_name="采购订单",null=True,blank=True,)   #供应商
    PO_Ststus = models.CharField("状态",max_length=1, choices=PO_STATUS_CHOICES,default='I',blank=False, null=False)
    PO_Description =  models.CharField("备注",max_length=200,null=True,blank=True,)
    PO_PurchaseRequest = models.ForeignKey(PurchaseRequest,verbose_name='采购申请',related_name="采购订单",null=True,blank=True,)
    PO_LastModify_Date = models.DateTimeField("最后操作时间",blank=False,null=False,auto_now=True)
    Project = models.ForeignKey(Project , verbose_name='项目',related_name='PurchaseOrders',blank=True,null=True,)
     
    def __unicode__(self):
        return self.PO_Title
    @property
    def Status(self):
        return self.PO_Ststus
    @property
    def get_Status_display(self):
        return self.get_PO_Ststus_display
    @property    
    def LastModify_Date(self):
        return self.PO_LastModify_Date
    @property    
    def ApplyMan(self):
        return self.PO_Employee
    @property    
    def Title(self):
        return self.PO_Title
    
    @property
    def get_url(self):
        return url_base + '/po/'+str(self.id)
    
    @property
    def Total(self):
        _total = self.PurchaseOrderDetail.aggregate(Sum('POD_Amount'))
        _total =  int((_total['POD_Amount__sum'] if _total['POD_Amount__sum'] else 0))
        return _total
    
    @property
    def PayTotal(self):
        _pay=Payment.objects.filter(Q(Status='O')&Q(PurchaseOrder=self)).aggregate(Sum('Amount'))
        _pay= int((_pay['Amount__sum'] if _pay['Amount__sum'] else 0))
        return _pay
    @property
    def PayTotalAudit(self):
        _pay=Payment.objects.filter(Q(Status__in=['P','O'])&Q(PurchaseOrder=self)).aggregate(Sum('Amount'))
        _pay= int((_pay['Amount__sum'] if _pay['Amount__sum'] else 0))
        return _pay
    
    class Meta:
        permissions = ()    
        verbose_name = "采购订单" 
        verbose_name_plural = "采购订单"
    @property
    def Can_Edit(self):
        return self.user==self.PO_Employee.Emp_User and self.PO_Ststus in ['I','B'] 
    @property
    def Can_Cancel(self):
        return self.user==self.PO_Employee.Emp_User and self.PO_Ststus in ['I','S','P','B','Z'] 
    @property
    def Can_Submit(self):#审核人和供应商不能为空
        return self.PO_Employee_Audit!=None and self.PO_Supplier!=None and self.user==self.PO_Employee.Emp_User and self.PO_Ststus in ['I','B'] 
    @property
    def Can_Audit(self):
        return self.PO_Employee_Audit and self.user==self.PO_Employee_Audit.Emp_User and self.PO_Ststus in ['S'] 
    @property
    def Can_Return(self):
        return (self.PO_Employee_Audit and self.user==self.PO_Employee_Audit.Emp_User and self.PO_Ststus in ['S']) 
    @property
    def Can_Buy(self):
        return ((func.in_group(self.user, u'采购')  and self.PO_Ststus in ['P'])) 
    @property
    def Can_Receipt(self):#收货，采购中状态
        return (func.in_group(self.user, u'仓库')  and self.PO_Ststus in ['Z'])  
    @property
    def Can_Pay(self):#收货，采购中状态
        return (func.in_group(self.user, u'财务')  and self.PO_Ststus in ['Z','F'])
        
    def Do(self,user,action):
        action = action.lower()
        if (action=='pass'):
            #通过：审批人可以操作，要写操作日志
            if self.Can_Audit:
                self.PO_Ststus = 'P'                
                self.save()
                self.WriteOperatorLog('审批通过',user,'')            
        elif (action=='deny'):
            #拒绝：审批人/采购 可以操作，要写操作日志
            if self.Can_Audit:
                self.PO_Ststus = 'D'                
                self.save()
                self.WriteOperatorLog('审批否决',user,'')
        elif (action=='submit'):
            #提交：建立者 可以操作，要写操作日志
            if self.Can_Submit:
                self.PO_Ststus = 'S' 
                self.save()
                self.WriteOperatorLog('提交',user,'')
        elif (action=='return'):
            #退回：审核人和采购 可以操作，要写操作日志
            if self.Can_Return:
                self.PO_Ststus = 'B' 
                self.save()
                self.WriteOperatorLog('退回',user,'退回之后可以重新修改之后再提交')
        elif (action=='cancel'):
            #退回：申请人 可以操作，要写操作日志
            if self.Can_Cancel:
                self.PO_Ststus = 'C' 
                self.save()
                self.WriteOperatorLog('取消',user,'')
        elif (action=='buy'):
            #退回：申请人 可以操作，要写操作日志
            if self.Can_Buy:
                self.PO_Ststus = 'Z' 
                self.save()
                self.WriteOperatorLog('采购中',user,'已经发送订单给供应商')
        elif (action=='receipt'):
            #退回：仓库可以操作，要写操作日志
            if self.Can_Receipt:
                #新建订单
                po = PurchaseReceipt()
                po.PR_Title = self.PO_Title
                po.PR_Supplier = self.PO_Supplier
                po.PR_CreateEmployee = Employee.GetEmployeeFromUser(user)
                po.PR_PurchaseOrder = self
                po.PR_Ststus = 'I'
                po.save()
                #订单项目
                for item in PurchaseOrderDetail.objects.filter(POD_PurchaseOrder=self):
                    pod = PurchaseReceiptDetail()
                    pod.PurchaseReceipt = po 
                    pod.Commodity = item.POD_Commodity                 
                    pod.Quanlity = item.POD_Quanlity
                    pod.save()
                    
                self.PO_Ststus = 'F' 
                self.save()
                self.WriteOperatorLog('完成',user,'已收货')
        elif (action=='pay'):
            #退回：仓库可以操作，要写操作日志
            if self.Can_Pay:
                #新建订单
                po = Payment()
                po.Title = self.PO_Title +u'支付'
                po.PurchaseOrder = self 
                po.Customer = self.PO_Supplier
                po.ApplyMan  = Employee.GetEmployeeFromUser(user)                
                po.PR_Ststus = 'I'
                po.save()
                
                self.WriteOperatorLog('支付',user,'创建一笔支付')
                
                return po.id
        else:
            pass
    
    def WriteOperatorLog(self,name,user,description):
        OperatorLog.WriteOperatorLog('PO', name, user, description,self.id)
        
    def GetOperatorLog(self):
        return OperatorLog.GetOperatorLog('PO', self.id)
    
    def save(self, *args, **kwargs):
        #do_something() 
        IsNew = False
        if self.id==None:
            IsNew = True
        super(PurchaseOrder, self).save(*args, **kwargs) # Call the "real" save() method.
        #do_something_else()
        if IsNew:
            self.WriteOperatorLog('新建',self.PO_Employee.Emp_User,'')
            
class PurchaseOrderDetail(models.Model):
    """
        采购订单明细（明细编号，采购订单编号，商品编码,数量,单价,金额）
        """    
    POD_PurchaseOrder = models.ForeignKey(PurchaseOrder,verbose_name='采购订单',related_name="PurchaseOrderDetail")
    POD_Commodity = models.ForeignKey(Commodity,verbose_name='物品',related_name="PurchaseOrderDetail")
    POD_Quanlity = models.IntegerField("数量")
    POD_Price = models.DecimalField("单价",max_digits=20,decimal_places=2,default=0)
    POD_Amount = models.DecimalField("金额",max_digits=20,decimal_places=2,default=0)
    def save(self, *args, **kwargs):
        #do_something() 
        #self.PRI_Price = self.PRI_Commodity.Com_Price
        self.POD_Amount = self.POD_Quanlity*self.POD_Price
        super(PurchaseOrderDetail, self).save(*args, **kwargs) # Call the "real" save() method.
        #do_something_else()
        
class Store(models.Model):
    """
    仓库（仓库编号,仓库名称,仓库地址,库管员,联系电话）
    """
    St_Name = models.CharField("仓库名称",max_length=50)
    St_Address = models.CharField("仓库地址",max_length=50,null=True)
    St_Manager = models.ForeignKey(Employee,verbose_name='管理员',related_name="管理仓库",null=True,)
    St_Telephone = models.CharField("联系电话",max_length=50)
    def __unicode__(self):
        return self.St_Name
    class Meta: 
        verbose_name = "仓库" 
        verbose_name_plural = "仓库"
class StoreSetting(models.Model):
    """
    商品库存警戒表（仓库编号，商品编码，库存下限，库存上限，备注）
    """
    SS_Store = models.ForeignKey(Store,verbose_name='仓库',related_name="商品库存警戒",null=True,blank=True)
    SS_Commodity = models.ForeignKey(Commodity,verbose_name='物品',related_name="商品库存警戒")
    SS_QuanlityDown = models.IntegerField("库存下限",null=True,blank=True)
    SS_QuanlityUp = models.IntegerField("库存上限",null=True,blank=True)
    SS_Memory = models.CharField("备注",max_length=50,null=True,blank=True)
    class Meta: 
        verbose_name = "仓库预警" 
        verbose_name_plural = "仓库预警"
    def __unicode__(self):
        return self.SS_Store.St_Name +'-' + self.SS_Commodity.Com_Name
    
Receipt_STATUS_CHOICES = (
        ('I', '创建中'),
        ('S', '提交验收'),
        ('P', '验收通过'),#最终状态
        ('C', '已取消'),#最终状态
        ('B', '被退回'),
     )

PurchaseReceiptStatusList = [
                             ('Can_Submit','submit','提交'),
                            ('Can_Cancel','cancel','取消'),
                            ('Can_Return','return','退回'),
                            ('Can_Audit','pass','验收通过'),
                            #('Can_Audit','deny','否决'),                             
                            ]
class PurchaseReceipt(base_user,models.Model):
    """
            采购收货单（采购收货编号，供应商编号，交货日期，制单日期，经手人，操作员，备注）
            """
    PR_Title  = models.CharField("标题",max_length=50)
    PR_PurchaseOrder = models.ForeignKey(PurchaseOrder,verbose_name='采购订单',related_name="PurchaseReceipt",null=True,blank=True,)
    PR_Supplier = models.ForeignKey(Supplier,verbose_name='供应商',related_name="PurchaseReceipt")
    PR_ReceiptDateTime = models.DateTimeField("交货日期",null=True,blank=True,)
    PR_CreateDateTime = models.DateTimeField("制单日期",auto_now_add=True)
    PR_CreateEmployee = models.ForeignKey(Employee,verbose_name='入库者',related_name="PurchaseReceiptStore")
    PR_ReceiptEmployee = models.ForeignKey(Employee,verbose_name='验收者',related_name="PurchaseReceiptAudit",null=True,blank=True,)
    PR_Description = models.CharField("备注",max_length=500,null=True,blank=True,)
    PR_Ststus = models.CharField("状态",max_length=1, choices=Receipt_STATUS_CHOICES,default='I',blank=False, null=False)
    PR_LastModify_Date = models.DateTimeField("最后操作时间",blank=False,null=False,auto_now=True)
    @property
    def get_url(self):
        return url_base + '/re/'+str(self.id)
    @property
    def Status(self):
        return self.PR_Ststus
    @property
    def get_Status_display(self):
        return self.get_PR_Ststus_display
    def __unicode__(self):
        return self.PR_Title
    @property    
    def LastModify_Date(self):
        return self.PR_LastModify_Date
    @property    
    def ApplyMan(self):
        return self.PR_CreateEmployee
    @property    
    def Title(self):
        return self.PR_Title
    class Meta: 
        verbose_name = "采购入库" 
        verbose_name_plural = "采购入库"
    @property
    def Can_Edit(self):
        return  func.in_group(self.user, u'仓库') and self.user==self.PR_CreateEmployee.Emp_User and self.PR_Ststus in ['I','B'] 
    @property
    def Can_Cancel(self):
        return self.user==self.PR_CreateEmployee.Emp_User and self.PR_Ststus in ['I','S','B'] 
    @property
    def Can_Submit(self):#审核人和供应商不能为空
        return self.PR_ReceiptDateTime!=None and self.PR_Supplier!=None and self.PR_ReceiptEmployee!=None and self.user==self.PR_CreateEmployee.Emp_User and self.PR_Ststus in ['I','B']
        #return False 
    @property
    def Can_Audit(self):
        return self.PR_ReceiptEmployee and self.user==self.PR_ReceiptEmployee.Emp_User and self.PR_Ststus in ['S'] 
    @property
    def Can_Return(self):
        return (self.PR_ReceiptEmployee and self.user==self.PR_ReceiptEmployee.Emp_User and self.PR_Ststus in ['S']) 

    def Do(self,user,action):
        action = action.lower()
        if (action=='pass'):
            #通过：审批人可以操作，要写操作日志
            if self.Can_Audit:
                self.PR_Ststus = 'P'                
                self.save()
                self.WriteOperatorLog('验收通过',user,'')    
                return        
        elif (action=='submit'):
            #提交：建立者 可以操作，要写操作日志
            #raise Exception("%s is submit." % self.Can_Submit ) #test
            if self.Can_Submit:
                self.PR_Ststus = 'S' 
                self.save()
                self.WriteOperatorLog('提交',user,'')
                return
        elif (action=='return'):
            #退回：审核人和采购 可以操作，要写操作日志
            if self.Can_Return:
                self.PR_Ststus = 'B' 
                self.save()
                self.WriteOperatorLog('退回',user,'退回之后可以重新修改之后再提交')
                return
        elif (action=='cancel'):
            #退回：申请人 可以操作，要写操作日志
            if self.Can_Cancel:
                self.PR_Ststus = 'C' 
                self.save()
                self.WriteOperatorLog('取消',user,'')       
                return 
        else:
            pass
        
        raise Exception(u"action="+action+u",非法的操作。")
 
    def WriteOperatorLog(self,name,user,description):
        OperatorLog.WriteOperatorLog('RE', name, user, description,self.id)
        
    def GetOperatorLog(self):
        return OperatorLog.GetOperatorLog('RE', self.id)
    
    def save(self, *args, **kwargs):
        #do_something() 
        IsNew = False
        if self.id==None:
            IsNew = True
        super(PurchaseReceipt, self).save(*args, **kwargs) # Call the "real" save() method.
        #do_something_else()
        if IsNew:
            self.WriteOperatorLog('新建',self.PR_CreateEmployee.Emp_User,'')
     
class PurchaseReceiptDetail(models.Model):
    """
        采购收货单明细（明细编号，采购收货编号，商品编码，库存数量）
        """  
    PurchaseReceipt = models.ForeignKey(PurchaseReceipt,verbose_name='采购入库',related_name="PurchaseReceiptDetail")
    Commodity = models.ForeignKey(Commodity,verbose_name='物品',related_name="PurchaseReceiptDetail")
    Quanlity = models.IntegerField("数量")
    Description = models.CharField("备注",max_length=50,null=True,blank=True,)

StockOut_STATUS_CHOICES = (
        ('I', '创建中'),
        ('S', '提交审批'),
        ('P', '审批通过'),
        ('D', '审批否决'),
        ('C', '已取消'),#最终状态
        ('B', '被退回'),
        ('O', '已出库'),#最终状态
     )
 

StockOutStatusList =[('Can_Submit','submit','提交'),
                            ('Can_Cancel','cancel','取消'),
                            ('Can_Return','return','退回'),
                            ('Can_Audit','pass','通过'),
                            ('Can_Audit','deny','否决'),
                            
                            ('Can_Out','out','出库'),
                            
                            ]
        
class StockOut(base_user,models.Model):
    """
    销售出库单（出库编号，客户编号，出库日期，备注，订单编号，制单人）
    """
    Title = models.CharField("标题",max_length=50)   
    Customer = models.ForeignKey(Customer,verbose_name='客户',related_name="StockOut",null=True,blank=True,)#客户编号    
    CreateDateTime = models.DateTimeField("出库日期",auto_now_add=True)    
    Description = models.CharField("备注",max_length=500,null=True,blank=True,) 
    OrderID = models.CharField("订单编号",max_length=50,null=True,blank=True,)
    ApplyMan = models.ForeignKey(Employee,verbose_name='申请者',related_name="StockOutApply")
    AuditMan = models.ForeignKey(Employee,verbose_name='审核者',related_name="StockOutAudit")
    StoreMan = models.ForeignKey(Employee,verbose_name='库管',related_name="StockOutStore",null=True,blank=True,)
    Ststus = models.CharField("状态",max_length=1, choices=StockOut_STATUS_CHOICES,default='I',blank=False, null=False)
    LastModify_Date = models.DateTimeField("最后操作时间",blank=False,null=False,auto_now=True)
    class Meta: 
        verbose_name = "领用出库" 
        verbose_name_plural = "领用出库"
    @property
    def Status(self):
        return self.Ststus
    @property
    def get_Status_display(self):
        return self.get_Ststus_display
    @property
    def get_url(self):
        return url_base + '/so/'+str(self.id)
    def __unicode__(self):
        return self.Title
    @property
    def Can_Edit(self):
        return self.user==self.ApplyMan.Emp_User and self.Ststus in ['I','B'] 
    @property
    def Can_Cancel(self):
        return self.user==self.ApplyMan.Emp_User and self.Ststus in ['I','S','B','P'] 
    @property
    def Can_Submit(self):#审核人和供应商不能为空
        return self.ApplyMan and self.user==self.AuditMan.Emp_User and self.Ststus in ['I','B'] 
    @property
    def Can_Audit(self):
        return self.AuditMan and self.user==self.AuditMan.Emp_User and self.Ststus in ['S'] 
    @property
    def Can_Return(self):
        return (self.AuditMan and self.user==self.AuditMan.Emp_User and self.Ststus in ['S'])
    @property
    def Can_Out(self):
        return (func.in_group(self.user, u'仓库')  and self.Ststus in ['P']) 

    def Do(self,user,action):
        action = action.lower()
        if (action=='pass'):
            #通过：审批人可以操作，要写操作日志
            if self.Can_Audit:
                self.Ststus = 'P'                
                self.save()
                self.WriteOperatorLog('审核通过',user,'')            
        elif (action=='submit'):
            #提交：建立者 可以操作，要写操作日志
            if self.Can_Submit:
                self.Ststus = 'S' 
                self.save()
                self.WriteOperatorLog('提交',user,'')
        elif (action=='return'):
            #退回：审核人和采购 可以操作，要写操作日志
            if self.Can_Return:
                self.Ststus = 'B' 
                self.save()
                self.WriteOperatorLog('退回',user,'退回之后可以重新修改之后再提交')
        elif (action=='cancel'):
            #退回：申请人 可以操作，要写操作日志
            if self.Can_Cancel:
                self.Ststus = 'C' 
                self.save()
                self.WriteOperatorLog('取消',user,'')     
        elif (action=='out'):
            #出库：申请人 可以操作，要写操作日志
            if self.Can_Out :
                self.Ststus = 'O' 
                self.StoreMan = Employee.GetEmployeeFromUser(user)
                self.save()
                self.WriteOperatorLog('出库',user,'')      
        else:
            pass
    
    def WriteOperatorLog(self,name,user,description):
        OperatorLog.WriteOperatorLog('SO', name, user, description,self.id)
        
    def GetOperatorLog(self):
        return OperatorLog.GetOperatorLog('SO', self.id)
    
    def save(self, *args, **kwargs):
        #do_something() 
        IsNew = False
        if self.id==None:
            IsNew = True
        super(StockOut, self).save(*args, **kwargs) # Call the "real" save() method.
        #do_something_else()
        if IsNew:
            self.WriteOperatorLog('新建',self.ApplyMan.Emp_User,'')
            
class StockOutItem(models.Model):
    """
    销售出库单明细（明细编号，出库编号，商品编码，数量，金额）
    """
    StockOut = models.ForeignKey(StockOut,verbose_name='领用出库',related_name="StockOutItems")
    Store = models.ForeignKey(Store,verbose_name='仓库',related_name="StockOutItems",null=True,blank=True,)     #仓库编号
    Commodity = models.ForeignKey(Commodity,verbose_name='物品',related_name="StockOutItems")
    Quanlity = models.IntegerField("数量")
    Description = models.CharField("备注",max_length=50,null=True,blank=True,)

PaymentStatusList =[('Can_Submit','submit','提交'),
                            ('Can_Cancel','cancel','取消'),
                            ('Can_Return','return','退回'),
                            ('Can_Audit','pass','通过'),
                            ('Can_Audit','deny','否决'),
                            ('Can_Pay','pay','支付'),
                            ]
Payment_STATUS_CHOICES = (
        ('I', '创建中'),
        ('S', '提交审批'),
        ('P', '审批通过'),
        ('D', '审批否决'),
        ('C', '已取消'),#最终状态
        ('B', '被退回'),
        ('O', '已支付'),#最终状态
     )
class Payment(base_user,models.Model):
    PurchaseOrder = models.ForeignKey(PurchaseOrder,verbose_name='订单',related_name="Payments",null=True,blank=True,)
    Customer = models.ForeignKey(Supplier,verbose_name='供应商',related_name="Payments",null=True,blank=True,)
    Title = models.CharField("标题",max_length=50)
    Amount = models.DecimalField("金额",max_digits=20,decimal_places=2,default=0)
    ApplyMan = models.ForeignKey(Employee,verbose_name='申请者',related_name="PaymentApply")
    AuditMan = models.ForeignKey(Employee,verbose_name='审核者',related_name="PaymentAudit",null=True,blank=True,)
    CreateDateTime = models.DateTimeField("创建日期",auto_now_add=True)
    Description = models.CharField("备注",max_length=50,null=True,blank=True,)
    PaymentSN = models.CharField("付款单号",max_length=50,null=True,blank=True,)
    Status = models.CharField("状态",max_length=1, choices=Payment_STATUS_CHOICES,default='I',blank=False, null=False)
    LastModify_Date = models.DateTimeField("最后操作时间",blank=False,null=False,auto_now=True)
    @property
    def get_url(self):
        return url_base + '/pa/'+str(self.id)
    class Meta: 
        verbose_name = "支付" 
        verbose_name_plural = "支付"
    def __unicode__(self):
        return self.Title    
     

    @property
    def OrderTotal(self):
        return self.PurchaseOrder.Total    
    @property
    def OrderPayTotal(self):
        return self.PurchaseOrder.PayTotal
    @property
    def OrderPayTotalAudit(self):
        return self.PurchaseOrder.PayTotalAudit
    
    
    @property
    def Can_Edit(self):
        return  func.in_group(self.user, u'财务') and self.user==self.ApplyMan.Emp_User and self.Status in ['I','B'] 
    @property
    def Can_Cancel(self):
        return  func.in_group(self.user, u'财务') and self.user==self.ApplyMan.Emp_User and self.Status in ['I','S','B','P'] 
    @property
    def Can_Submit(self):#审核人和供应商不能为空
        return func.in_group(self.user, u'财务') and self.AuditMan !=None and self.Status in ['I','B'] 
    @property
    def Can_Audit(self):
        return self.AuditMan !=None and self.user==self.AuditMan.Emp_User and self.Status in ['S'] 
    @property
    def Can_Return(self):
        return (self.AuditMan and self.user==self.AuditMan.Emp_User and self.Status in ['S'])
    @property
    def Can_Pay(self):
        return (func.in_group(self.user, u'财务')  and self.Status in ['P']) 

    def Do(self,user,action):
        action = action.lower()
        self.user = user
        if (action=='pass'):
            #通过：审批人可以操作，要写操作日志
            if self.Can_Audit:
                self.Status = 'P' 
                self.save()
                self.WriteOperatorLog('审核通过',user,'')
        elif (action=='deny'):
            #通过：审批人可以操作，要写操作日志
            if self.Can_Audit:
                self.Status = 'D' 
                self.save()
                self.WriteOperatorLog('审核否决',user,'')        
        elif (action=='submit'):
            #提交：建立者 可以操作，要写操作日志
            if self.Can_Submit:
                self.Status = 'S' 
                self.save()
                self.WriteOperatorLog('提交',user,'')
        elif (action=='return'):
            #退回：审核人和采购 可以操作，要写操作日志
            if self.Can_Return:
                self.Status = 'B' 
                self.save()
                self.WriteOperatorLog('退回',user,'退回之后可以重新修改之后再提交')
        elif (action=='cancel'):
            #退回：申请人 可以操作，要写操作日志
            if self.Can_Cancel:
                self.Status = 'C' 
                self.save()
                self.WriteOperatorLog('取消',user,'')     
        elif (action=='pay'):
            #出库：申请人 可以操作，要写操作日志
            if self.Can_Pay :
                self.Status = 'O' 
                self.StoreMan = Employee.GetEmployeeFromUser(user)
                self.save()
                self.WriteOperatorLog('支付',user,'')      
        else:
            pass
    
    def WriteOperatorLog(self,name,user,description):
        OperatorLog.WriteOperatorLog('PA', name, user, description,self.id)
        
    def GetOperatorLog(self):
        return OperatorLog.GetOperatorLog('PA', self.id)
    
    def save(self, *args, **kwargs):
        #do_something() 
        IsNew = False
        if self.id==None:
            IsNew = True
        super(Payment, self).save(*args, **kwargs) # Call the "real" save() method.
        #do_something_else()
        if IsNew:
            self.WriteOperatorLog('新建',self.ApplyMan.Emp_User,'')
        else:
            self.WriteOperatorLog('修改',self.ApplyMan.Emp_User,'')
      